package com.pwc.conversionTool.rest;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletContext;

import org.apache.commons.io.FileUtils;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.pwc.conversionTool.IO.FileOperation;
import com.pwc.conversionTool.Manager.XMLConfigImpl;
import com.pwc.conversionTool.config.UploadFileView;
import com.pwc.conversionTool.csv.CsvHelper;
import com.pwc.conversionTool.csv.CsvManager;
import com.pwc.conversionTool.csv.CsvUpload;

@Controller
public class CsvRest {
	private static final Logger logger = LoggerFactory.getLogger(CsvRest.class);

	@Autowired
	public ServletContext context;

	@RequestMapping(value = "/rest/csv/viewAllFiles", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody List<List<String>> viewAllFiles(String path) {
		return UploadFileView.initial(path).GetFiles();
	}

	@RequestMapping(value = "/rest/csv/viewOneFile", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody List<String[]> viewOneFile(String fileName, String path) {

		String filepath = path + File.separator + fileName;

		List<String[]> list = null;
		try {
			list = new CsvHelper(filepath).getAll();
		} catch (Exception e) {
			logger.error("error in viewOneFile");
			logger.error(Arrays.toString(e.getStackTrace()));
		}

		return list;

	}

	@RequestMapping(value = "/rest/csv/deleteOneFile", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody void deleteOneFile(String fileName, String path) {
		try {
			String filepath = path + File.separator + fileName;
			File file = new File(filepath);
			FileOperation.deleteFile(file);
		} catch (Exception e) {
			logger.error("error in deleteOneFile");
			logger.error(Arrays.toString(e.getStackTrace()));
		}
		
	}

	@RequestMapping(value = "/rest/csv/deleteAllFiles", method = RequestMethod.POST, produces = "application/json")
	public @ResponseBody void deleteAllFiles(String path) {
		try {
			CsvManager.initial(path).deleteAllFiles();
		} catch (Exception e) {
			logger.error("error in deleteAllFiles");
			logger.error(Arrays.toString(e.getStackTrace()));
		}

	}

}
